package com.gxa.shop.servlet.product;

import com.alibaba.fastjson.JSON;
import com.gxa.shop.bean.vo.CategoryOption;
import com.gxa.shop.bean.vo.ProductVo;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.category.CategoryService;
import com.gxa.shop.service.category.impl.CategoryServiceImpl;
import com.gxa.shop.service.prodect.ProductService;
import com.gxa.shop.service.prodect.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * com.gxa.shop.servlet.product
 * User: 刁彦侨
 * Date: 2024/12/21 10:02
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
@WebServlet(name = "GetAllProduct",value = "/product/getGoods")
public class GetAllProductServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CategoryService categoryService=new CategoryServiceImpl();
        ProductService productService=new ProductServiceImpl();
        List<CategoryOption> categoryList= categoryService.findAllList();
        List<Map<String, Object>> categoriesWithGoods = new ArrayList<>();

        for (CategoryOption category : categoryList) {
            List<ProductVo> goods = productService.queryByCategoryId(category.getCategoryId());
            Map<String, Object> categoryData = new HashMap<>();
            categoryData.put("goods",goods);
            categoryData.put("categoryName",category.getCategoryName());
            categoryData.put("categoryId",category.getCategoryId());
            categoriesWithGoods.add(categoryData);
        }
        R r = R.ok(categoriesWithGoods);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        //r=list!=null?R.ok().addData("list",list):R.ok("没有分类信息");
        PrintWriter writer = resp.getWriter();
        String  result= JSON.toJSONString(r);
        System.out.println("FindAllListServlet:"+result);
        writer.write(result);
        writer.flush();
        writer.close();
    }
}
